package com.crawler.thr;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

/**

 * 线程池

 * 

 * @ClassName ExecutorService

 * @Description TODO

 * @author TL

 * @date 2015-8-4 下午02:01:13

 * 

 */
public class ExecutorService {
    private ThreadPoolExecutor executor; // 线程池

    private ListeningExecutorService service; // Guava 线程池


    public ExecutorService(int nThreads) {
        executor = new ThreadPoolExecutor(nThreads, nThreads, 1, TimeUnit.HOURS, new ArrayBlockingQueue<Runnable>(
                nThreads), new ThreadPoolExecutor.CallerRunsPolicy());
        // service =


        // MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(nThreads));


        service = MoreExecutors.listeningDecorator(executor);
    }

    /**
     * 
     * 方法描述： 添加线程队列
     * 
     * @author TL
     * @date 2015-8-4 下午01:55:46
     * @param <V>
     * @param callable
     * @param futurecallback
     * @return
     */
    public <V> void addCallback(Callable<V> callable, FutureCallback<V> futurecallback) {
        Futures.addCallback(service.submit(callable), futurecallback);
    }
    
    public <V> ListenableFuture<V> submit(Callable<V> callable){
        return service.submit(callable);
    }
    
    public void submit(Runnable runnable){
        service.submit(runnable);
    }

    /**

     * 

     * 方法描述：关闭线程对象

     * 

     * @author TL

     * @date 2015-8-4 下午01:56:40

     */
    public void shutdown() {
        service.shutdown();
    }
    
    public void shutdownNow() {
        service.shutdownNow();
    }

    /**

     * 判断线程是否全部执行结束

     * 

     * @author TL

     * @date 2015-8-4 下午01:58:16

     * @return

     */
    public boolean isTerminated() {
        return service.isTerminated();
    }

    /**

     * 等待 全部线程结束

     * 

     * @author dong.tl@neusoft.com

     * @date 2015-8-10 下午02:41:16

     */
    public void waitOver() {
        shutdown();
        do {
            try {
                Thread.sleep(800);
            } catch (InterruptedException e) {
            }
        } while (!service.isTerminated());
    }

}
